package me.firstapp.manage.cqssc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;

import me.firstapp.common.json.AbstractJsonObject;
import me.firstapp.common.json.PageObject;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.module.zerone.JsonCqsscLotteryResult;
import me.firstapp.common.utils.DateUtils;
import me.firstapp.common.utils.ResponseUtils;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.manage.common.BaseManage;
import me.firstapp.manage.utils.BizData4Page;
import me.firstapp.spi.zerone.CqsscService;

@Controller
@RequestMapping(value = "/cqsscManage")
public class LotteryResultManageAct extends BaseManage {

	@Autowired
	private CqsscService cqsscService;

	@ResponseBody
	@RequestMapping(value = "/findLotteryResultPage.do", method = RequestMethod.POST)
	public void findLotteryResultPage(@RequestParam Map<String, Object> conditions, HttpServletRequest request,
			HttpServletResponse response) {

		try {
			// 搜索条件
			Map<String, Object> searchParams = new HashMap<>();
			String sSearchJson = (String) conditions.get("sSearch");
			if (StrUtils.isNotNULL(sSearchJson)) {
				JSONObject jsonObject = JSONObject.parseObject(sSearchJson);
				if (jsonObject != null) {
					Set<String> keySet = jsonObject.keySet();
					for (String key : keySet) {
						searchParams.put(key, jsonObject.get(key));
					}
				}
			}
			// 排序字段
			String mDataProp = "mDataProp_" + conditions.get("iSortCol_0");
			mDataProp = conditions.get(mDataProp).toString().replace("Str", "");
			// 排序方式
			String sSortDir_0 = (String) conditions.get("sSortDir_0");
			// 页容
			String iDisplayLengthStr = (String) conditions.get("iDisplayLength");
			// 是开始数不是当前页数...
			String iDisplayStartStr = (String) conditions.get("iDisplayStart");
			if (StrUtils.isNotNULL(iDisplayLengthStr) && StrUtils.isNotNULL(iDisplayStartStr)) {
				Integer iDisplayLength = Integer.valueOf(iDisplayLengthStr);
				Integer iDisplayStart = Integer.valueOf(iDisplayStartStr);
				// 当前页数
				Integer pageNo = iDisplayStart / iDisplayLength + 1;
				PageObject<JsonCqsscLotteryResult> adPage = cqsscService.findCqsscLotteryResultPage(pageNo,
						iDisplayLength, searchParams, mDataProp, sSortDir_0);
				SingleObject<Object> result = new SingleObject<Object>();
				BizData4Page<JsonCqsscLotteryResult> bizData4Page = new BizData4Page<JsonCqsscLotteryResult>();
				bizData4Page.setUserdata(conditions);
				if (adPage.getPage() != null) {
					bizData4Page.setPage(adPage.getPage().getPageNo());
					bizData4Page.setPagesize(adPage.getPage().getPageSize());
					bizData4Page.setRecords(adPage.getPage().getTotalCount());
					bizData4Page.setRows(new ArrayList<JsonCqsscLotteryResult>(adPage.getPage().getList()));
					bizData4Page.setTotal(adPage.getPage().getTotalCount());
				}

				result.setCode(adPage.getCode());
				result.setMsg(adPage.getMsg());
				result.setObject(bizData4Page);
				ResponseUtils.renderJson(response, result);
			}
		} catch (Exception e) {
			e.printStackTrace();
			AbstractJsonObject abstractJsonObject = new AbstractJsonObject();
			abstractJsonObject.setCode("error");
			abstractJsonObject.setMsg("发生未知错误");
			ResponseUtils.renderJson(response, abstractJsonObject);
		}
	}

	@RequestMapping(value = "/addLotteryResult.do", method = RequestMethod.POST)
	public void addLotteryResult(String issueNo, String prizeNo, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<JsonCqsscLotteryResult> result = cqsscService.addCqsscLotteryResult(issueNo, prizeNo);
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/addBatch.do", method = RequestMethod.POST)
	public void addBatch(String mDateStr, String startDateStr, String endDateStr, HttpServletRequest request,
			HttpServletResponse response) {
		if (StrUtils.isNotNULL(mDateStr)) {
			apiDoV2(mDateStr);
		} else {
			List<String> list = DateUtils.getEveryday(startDateStr, endDateStr);
			for (String string : list) {

				apiDoV2(string);
				try {
					Thread.sleep(4000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

	private void apido(String mDateStr) {
		// StringBuilder url = new
		// StringBuilder("http://t.apiplus.net/daily.do");
		RestTemplate restTemplate = new RestTemplate();
		mDateStr = mDateStr.replace("-", "").trim();
		for (int i = 1; i < 121; i++) {
			String issueno = "";
			if (i < 10) {
				issueno = mDateStr + "-00" + i;
			} else if (i > 9 && i < 100) {
				issueno = mDateStr + "-0" + i;
			} else if (i > 99) {
				issueno = mDateStr + "-" + i;
			}
			StringBuilder url = new StringBuilder("http://api.jisuapi.com/caipiao/query");
			url.append("?appkey=318591dc28186875&caipiaoid=73");
			url.append("&issueno=").append(issueno);

			JSONObject resultJson = null;
			try {
				System.out.println("调用[" + mDateStr + "]api开始");
				ResponseEntity<String> responseEntity = restTemplate.exchange(url.toString(), HttpMethod.GET, null,
						String.class);
				System.out.println("调用[" + mDateStr + "]api结束，返回结果为:" + responseEntity.getBody());
				resultJson = JSONObject.parseObject(responseEntity.getBody());
				String status = resultJson.getString("status");
				if ("0".equals(status)) {
					JSONObject jSONObject = resultJson.getJSONObject("result");
					String issueNo = jSONObject.getString("issueno");
					String prizeNo = jSONObject.getString("number").trim().replace(" ", "");
					cqsscService.addCqsscLotteryResult(issueNo, prizeNo);
				}
			} catch (RestClientException e) {
				e.printStackTrace();
			}
		}
	}

	private void apiDoV2(String mDateStr) {
		RestTemplate restTemplate = new RestTemplate();
		mDateStr = mDateStr.replace("-", "").trim();

		StringBuilder url = new StringBuilder(
				"http://api.kaijiangtong.com/lottery/?name=cqssc&format=json&uid=762153&token=208ba7e76a77546d2354a84fbbc5068e34f965a5");
		url.append("&date=").append(mDateStr);
		JSONObject resultJson = null;
		try {
			System.out.println("调用[" + mDateStr + "]api开始");
			ResponseEntity<String> responseEntity = restTemplate.exchange(url.toString(), HttpMethod.GET, null,
					String.class);
			System.out.println("调用[" + mDateStr + "]api结束，返回结果为:" + responseEntity.getBody());
			resultJson = JSONObject.parseObject(responseEntity.getBody());

			if (null != resultJson) {
				Set<String> keys = resultJson.keySet();
				for (String key : keys) {
					String issueNo = key.substring(0, 8) + "-" + key.substring(8, 11);
					JSONObject jsonObject = resultJson.getJSONObject(key);
					String prizeNo = jsonObject.getString("number").replace(",", "").trim();
					cqsscService.addCqsscLotteryResult(issueNo, prizeNo);
				}
			}

		} catch (RestClientException e) {
			e.printStackTrace();
		}
	}
}
